#include<iostream>
#include<thread>
#include<vector>
#include<string>
#include<list>
#include<mutex>

class Mathadd {
private:
    std::mutex mylock;
    int ans;
public:
    Mathadd(int _ans): ans(_ans){}
    int getAns();
    void add1();
    void add2();
};

int Mathadd::getAns() {
    return ans;
}

void Mathadd::add1() {
	for (int i = 1; i < 5000; i++) {
		std::unique_lock<std::mutex> myuniquelock(mylock, std::defer_lock);
        if (myuniquelock.try_lock()) {
            ans += i;
        }
	}
}

void Mathadd::add2() {
	for (int i = 5000; i <= 10000; i++) {
		std::lock_guard<std::mutex> myuniquelock(mylock);
		ans += i;
	}
}

int fun() {
	int sum = 0;
	for (int i = 1; i <= 10000; i++) {
		sum += i;
	}
	return sum;
}

int main()
{
	Mathadd mymath(0);
	std::thread t1(&Mathadd::add1, std::ref(mymath));
	std::thread t2(&Mathadd::add2, std::ref(mymath));
	t1.join();
	t2.join();
	std::cout << "线程加 : " << mymath.getAns() << std::endl;
	std::cout << "直接加 : " << fun() << std::endl;
	return 0;
}
